package com.suptrack.web.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;





import com.suptrack.crypt.BCrypt;
import com.suptrack.entity.Position;
import com.suptrack.entity.User;
import com.suptrack.service.UserService;



/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet(name = "ResgisterServlet", urlPatterns = {"/Register"})
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
@EJB
UserService userservice;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		
		String adresse = req.getParameter("adresse");
		String password = BCrypt.hashpw( req.getParameter("password"), BCrypt.gensalt());
		String mail=req.getParameter("mail");
		String nom =req.getParameter("lastname");
		String prenom = req.getParameter("firstname");
		String pseudo = req.getParameter("username");
		String tel = req.getParameter("tel");
		String creditcard = req.getParameter("creditcard");
	//test presence d'un utilisateur avec le meme nom , si on retour message erreur .
		User userinbase = userservice.getUserByName(pseudo);
		if (userinbase!=null){
			
		
			
			//add message erreur
				resp.sendRedirect(req.getServletContext().getContextPath()+"/index");
			}
			else
			{
		User usertmp = new User();
		usertmp.setFirstName(prenom);
		usertmp.setLastName(nom);
		usertmp.setPostalAdress(adresse);
		usertmp.setMailAdress( mail);
		usertmp.setPassword( password);
		usertmp.setPhoneNumber(tel);
		usertmp.setCreditcard(creditcard);
		
		usertmp.setAccType(false);
		usertmp.setUserName(pseudo);
		
		
		
		

		
		userservice.addUserService(usertmp);
//		pour autolog
		req.setAttribute("pseudo", pseudo);
		req.setAttribute("password", password);
		
		
		
		req.getRequestDispatcher("/login").forward(req, resp);
		//resp.sendRedirect(req.getServletContext().getContextPath()+"/login");
			}
}
}
